package com.pet.platform.controller;

import com.pet.platform.common.PageResult;
import com.pet.platform.common.Result;
import com.pet.platform.dto.OrderDTO;
import com.pet.platform.entity.Order;
import com.pet.platform.entity.Product;
import com.pet.platform.exception.BusinessException;
import com.pet.platform.mapper.ProductMapper;
import com.pet.platform.service.OrderService;
import com.pet.platform.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;
    
    @Autowired
    private ProductMapper productMapper;

    @PostMapping
    public Result<OrderDTO> createOrder(@Valid @RequestBody OrderDTO orderDTO) {
        return Result.success(convertToDTO(orderService.createOrder(orderDTO)));
    }
    
    /**
     * 从购物车创建订单
     * @param requestMap 请求参数，包含addressId、paymentMethod、remark和items
     * @return 创建的订单
     */
    @PostMapping("/cart")
    public Result<OrderDTO> createOrderFromCart(@RequestBody Map<String, Object> requestMap) {
        // 验证参数
        if (!requestMap.containsKey("addressId")) {
            throw new BusinessException("收货地址不能为空");
        }
        if (!requestMap.containsKey("paymentMethod")) {
            throw new BusinessException("支付方式不能为空");
        }
        if (!requestMap.containsKey("items") || !(requestMap.get("items") instanceof List)) {
            throw new BusinessException("订单项不能为空");
        }
        
        Long addressId = Long.valueOf(requestMap.get("addressId").toString());
        String paymentMethod = (String) requestMap.get("paymentMethod");
        String remark = requestMap.containsKey("remark") ? (String) requestMap.get("remark") : "";
        
        List<Map<String, Object>> itemsMap = (List<Map<String, Object>>) requestMap.get("items");
        
        // 创建订单DTO
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setUserId(SecurityUtil.getCurrentUserId());
        
        // 生成订单号
        String orderNo = generateOrderNo();
        orderDTO.setOrderNo(orderNo);
        
        // 创建订单项列表
        List<OrderDTO.OrderItemDTO> orderItems = new ArrayList<>();
        // 计算订单总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        
        for (Map<String, Object> itemMap : itemsMap) {
            if (!itemMap.containsKey("productId") || !itemMap.containsKey("quantity")) {
                throw new BusinessException("订单项信息不完整");
            }
            
            Long productId = Long.valueOf(itemMap.get("productId").toString());
            Integer quantity = Integer.valueOf(itemMap.get("quantity").toString());
            
            // 获取商品信息
            Product product = productMapper.findById(productId)
                .orElseThrow(() -> new BusinessException("商品不存在: " + productId));
            
            // 创建订单项
            OrderDTO.OrderItemDTO orderItemDTO = new OrderDTO.OrderItemDTO();
            orderItemDTO.setProductId(productId);
            orderItemDTO.setQuantity(quantity);
            orderItemDTO.setPrice(product.getPrice());
            
            // 计算该项总价并累加到订单总金额
            BigDecimal itemTotal = product.getPrice().multiply(BigDecimal.valueOf(quantity));
            totalAmount = totalAmount.add(itemTotal);
            
            orderItems.add(orderItemDTO);
        }
        
        // 设置订单信息
        orderDTO.setOrderItems(orderItems);
        orderDTO.setTotalAmount(totalAmount);
        // 设置地址ID
        orderDTO.setAddressId(addressId);
        // 设置支付方式
        orderDTO.setPaymentMethod(paymentMethod);
        // 设置备注
        orderDTO.setRemark(remark);
        
        // 调用服务创建订单
        Order order = orderService.createOrder(orderDTO);
        return Result.success(convertToDTO(order));
    }
    
    /**
     * 生成订单号
     * 格式：年月日时分秒+4位随机数
     * @return 订单号
     */
    private String generateOrderNo() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 格式化为yyyyMMddHHmmss
        String timeStr = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        
        // 生成4位随机数
        Random random = new Random();
        int randomNum = random.nextInt(10000);
        String randomStr = String.format("%04d", randomNum);
        
        // 组合成订单号
        return timeStr + randomStr;
    }

    @GetMapping("/{id}")
    public Result<OrderDTO> getOrderDetail(@PathVariable Long id) {
        return Result.success(orderService.getOrderById(id));
    }

    @GetMapping("/my")
    public Result<PageResult<OrderDTO>> getMyOrders(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        PageResult<Order> pageResult = orderService.getUserOrders(SecurityUtil.getCurrentUserId(), pageNum, pageSize);
        List<OrderDTO> orderDTOs = pageResult.getList().stream()
            .map(this::convertToDTO)
            .collect(Collectors.toList());
        return Result.success(new PageResult<>(pageResult.getTotal(), orderDTOs));
    }

    @GetMapping("/my/status/{status}")
    public Result<PageResult<OrderDTO>> getMyOrdersByStatus(
            @PathVariable Integer status,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        PageResult<Order> pageResult = orderService.getOrdersByUserIdAndStatus(SecurityUtil.getCurrentUserId(), status, pageNum, pageSize);
        List<OrderDTO> orderDTOs = pageResult.getList().stream()
            .map(this::convertToDTO)
            .collect(Collectors.toList());
        return Result.success(new PageResult<>(pageResult.getTotal(), orderDTOs));
    }

    @PostMapping("/{id}/cancel")
    public Result<Void> cancelOrder(@PathVariable Long id) {
        orderService.cancelOrder(id);
        return Result.success();
    }

    @PostMapping("/{id}/pay")
    public Result<Void> payOrder(@PathVariable Long id, @RequestBody Map<String, String> requestMap) {
        String paymentMethod = requestMap.get("paymentMethod");
        if (paymentMethod == null || paymentMethod.isEmpty()) {
            throw new BusinessException("支付方式不能为空");
        }
        orderService.payOrder(id, paymentMethod);
        return Result.success();
    }

    @PostMapping("/{id}/confirm")
    public Result<Void> confirmReceive(@PathVariable Long id) {
        orderService.confirmReceive(id);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteOrder(@PathVariable Long id) {
        orderService.deleteOrder(id);
        return Result.success();
    }

    private OrderDTO convertToDTO(Order order) {
        if (order == null) {
            return null;
        }
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setId(order.getId());
        orderDTO.setUserId(order.getUserId());
        orderDTO.setTotalAmount(order.getTotalAmount());
        orderDTO.setStatus(order.getStatus());
        orderDTO.setCreatedTime(order.getCreatedTime());
        orderDTO.setUpdatedTime(order.getUpdatedTime());
        orderDTO.setOrderNo(order.getOrderNo());
        orderDTO.setAddressId(order.getAddressId());
        orderDTO.setPaymentMethod(order.getPaymentMethod());
        orderDTO.setRemark(order.getRemark());
        
        if (order.getOrderItems() != null) {
            List<OrderDTO.OrderItemDTO> orderItemDTOs = order.getOrderItems().stream()
                .map(item -> {
                    OrderDTO.OrderItemDTO itemDTO = new OrderDTO.OrderItemDTO();
                    itemDTO.setId(item.getId());
                    itemDTO.setProductId(item.getProductId());
                    itemDTO.setQuantity(item.getQuantity());
                    itemDTO.setPrice(item.getPrice());
                    
                    // 获取商品名称和图片URL
                    try {
                        com.pet.platform.entity.Product product = productMapper.findById(item.getProductId()).orElse(null);
                        if (product != null) {
                            itemDTO.setProductName(product.getName());
                            itemDTO.setImageUrl(product.getImageUrl());
                            System.out.println("设置商品图片: " + product.getImageUrl() + " 商品ID: " + item.getProductId());
                        } else {
                            itemDTO.setProductName("未知商品");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        itemDTO.setProductName("未知商品");
                    }
                    
                    return itemDTO;
                })
                .collect(Collectors.toList());
            orderDTO.setOrderItems(orderItemDTOs);
        }
        
        return orderDTO;
    }
} 